package com.demo.mq.rocket.consumer.simple;

import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.MessageExt;

import java.time.LocalDateTime;
import java.util.List;

import static com.demo.mq.rocket.consumer.Const.ROCKET_DEFAULT_GROUP;
import static com.demo.mq.rocket.consumer.Const.ROCKET_NAMESRVADDR;

/**
 * 推模式:服务器推送给消费者
 */
public class SimplePushConsumer {

    public static void main(String[] args) throws InterruptedException, MQClientException {

        // 指定组
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer(ROCKET_DEFAULT_GROUP);
        // 指定NameService  的地址,多个使用 ; 隔开
        consumer.setNamesrvAddr(ROCKET_NAMESRVADDR);
        // 指定topic
        consumer.subscribe("simple_topic", "*");
        // 消费消息
        consumer.registerMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs,
                                                            ConsumeConcurrentlyContext context) {
                for (MessageExt msg : msgs) {
                    System.out.println(LocalDateTime.now() + ":" + new String(msg.getBody()));
                }
                return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
            }
        });

        consumer.start();

        System.out.printf("消费者已启动.%n");
    }

}
